//
//  FolderType.swift
//  Casecord
//
//  Created by baozi on 2024/1/2.
//

import Foundation
enum FolderType: String {
    case photo, video
    
    var url: URL? {
        let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        guard var path = urls.first else { return nil }
        path.appendPathComponent(self.rawValue)
        if !FileManager.default.fileExists(atPath: path.path) {
            do {
                try FileManager.default.createDirectory(atPath: path.path, withIntermediateDirectories: true)
            } catch {
                return nil
            }
        }
        return path
    }
}

enum CustomFileError: Error {
    case notFound(String)
    case badForder(FolderType)
}

extension FileManager {
    // 文件是否存在
    func checkFileExist(name: String, type: FolderType) -> Bool {
        guard let url = type.url?.appendingPathComponent(name), FileManager.default.fileExists(atPath: url.path) else {
            return false
        }
        return true
    }
    
    // get data 获取数据
    func getData(name: String, type: FolderType) throws -> Data {
        guard let path = type.url?.appendingPathComponent(name) else {
            throw CustomFileError.badForder(type)
        }
        guard FileManager.default.fileExists(atPath: path.path) else {
            throw CustomFileError.notFound(path.path)
        }
        return try Data(contentsOf: path)
    }
    
    // set data 设置数据
    func setData(data: Data, name: String, type: FolderType) throws {
        guard let path = type.url?.appendingPathComponent(name) else {
            throw CustomFileError.badForder(type)
        }
        try data.write(to: path)
    }
    
    // 删除某项
    func removeItem(name: String, type: FolderType) throws {
        guard self.checkFileExist(name: name, type: type) else {
            throw CustomFileError.notFound(name)
        }
        guard let url = type.url else {
            throw CustomFileError.badForder(type)
        }
        let appUrl = url.appendingPathComponent(name)
        try FileManager.default.removeItem(at: appUrl)
    }
    
    
    // 删除整个路径文件夹
    func removeItem(type: FolderType) throws {
        guard let url = type.url else {
            throw CustomFileError.badForder(type)
        }
        try self.removeItem(at: url)
    }
    
    
}
